const newsTabContainer = document.querySelector(".news-tabs-container");
const tabHighlight = document.querySelector(".tab-highlight");
const newsTabItems = document.querySelectorAll(".news-tab-item");
const newsNavSpan = document.getElementById("nav-span");
const newsLists = document.querySelectorAll(".list-box");
let activeTab = newsTabItems[0];

let resizeTimer;
function moveHighlight(tab) {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(() => {
    const rect = tab.getBoundingClientRect();
    const containerRect = newsTabContainer.getBoundingClientRect();

    tabHighlight.style.width = `${rect.width}px`;
    tabHighlight.style.transform = `translateX(${
      rect.left - containerRect.left
    }px)`;
  }, 50);
}

newsTabItems.forEach((tab, index) => {
  // tab.addEventListener("mouseenter", (e) => {
  //   moveHighlight(e.target);
  // });
  tab.addEventListener("click", function (e) {
    newsLists.forEach(function (list) {
      list.classList.remove("show");
    });
    newsLists[index].classList.add("show");
    newsNavSpan.innerText = `> ${e.target.innerText}`;
    activeTab = e.target;
    moveHighlight(e.target);
  });
});

window.addEventListener("resize", () => {
  moveHighlight(activeTab);
});

window.addEventListener("load", () => {
  moveHighlight(activeTab);
});

// newsTabContainer.addEventListener("mouseleave", () => {
//   moveHighlight(activeTab);
// });

let urlParams = new URLSearchParams(window.location.search);
let position = urlParams.get("position");
if (position) {
  position = decodeURIComponent(position);
  position = position.replace(/"/g, "");
  console.log(position);
  position = Number(position);
  activeTab = newsTabItems[position]

  moveHighlight(activeTab);
  // 初始化
  newsLists.forEach(function (list) {
    list.classList.remove("show");
  });
  newsLists[position].classList.add("show");
  newsNavSpan.innerText = `> ${activeTab.innerText}`;
}
